
<?php
 
// error_reporting(E_ALL);
// ini_set("display_errors", 1);
// ini_set('display_startup_errors', 1);
// error_reporting(-1);

 
 include_once "../common/base.php";
 require_once('lib/PHPMailerAutoload.php');
 require 'markov.php';
 require_once('lib/ImapMailbox.php');
 
class sender
{
    private $_db;
	private $mailer;
	
    public function __construct($db=NULL)
    {
        if(is_object($db))
        {
            $this->_db = $db;
        }
        else
        {
            $dsn = "mysql:host=".DB_HOST.";dbname=".DB_NAME;
            $this->_db = new PDO($dsn, DB_USER, DB_PASS);
        }
	}
	
	public function init(){
        $this->log_level = 4;
		$this->mailer = new PHPMailer;
	}
	
	public function getMailsToSend($interval){
		$mails = array();
		$time = date("Y-m-d H:i:s", strtotime("+{$interval} minutes", time()));
		
		$trans_id = rand(1000,9999);
		
		$sql = "UPDATE send_mail SET trans_id = :trans_id
                WHERE
                STR_TO_DATE(fire,'%Y-%m-%d %H:%i:%s') < STR_TO_DATE(:time,'%Y-%m-%d %H:%i:%s') AND trans_id = 0 LIMIT 100;
                ";

        if($stmt = $this->_db->prepare($sql)) {
            $stmt->bindParam(":time", $time, PDO::PARAM_STR);
            $stmt->bindParam(":trans_id", $trans_id, PDO::PARAM_INT);
            $stmt->execute();
        }
        else
        {
            echo "Error! Sorry, Error in SQL.";
        }
		
		//Fetch
		$sql = "SELECT * FROM send_mail
                WHERE
                trans_id = :trans_id
				";
        if($stmt = $this->_db->prepare($sql)) {
			$stmt->bindParam(":trans_id", $trans_id, PDO::PARAM_INT);
            $stmt->execute();
            if($stmt->rowCount()!=0) 
			{
				for($i=0 ; $i<$stmt->rowCount() ; $i++){
    				$row = $stmt->fetch();
					array_push($mails, $row);
				}
            }
			else
			{
				//echo "No messages defined in any campaign.";
			}
		}
		else
		{
        	echo "Error! Sorry, Error in SQL.";
        }
		
		//UPDATE
		$sql = "DELETE FROM send_mail
                WHERE
                trans_id = :trans_id
                ";
        if($stmt = $this->_db->prepare($sql)) {
			$stmt->bindParam(":trans_id", $trans_id, PDO::PARAM_INT);
            $stmt->execute();
		}
		return $mails;	
	}
	
	public function doJob(){
		//delete from table where count = count(message)+1 for each from
		
		
		//Get the mails of next 2 mins with isFired = 0
		$interval = 2;
		$send_mails = $this->getMailsToSend($interval);
		//var_dump($send_mails);
		$this->send_mail($send_mails);
    } 
   
    public function getAliasInfo($mail_id){
		$gmail = "@gmail.com";
		$hotmail = "@hotmail.com";
		$yahoo = "@yahoo.com";
		$takethemail = "@takethemail.com";
		
		if(strstr($mail_id,$gmail) != false){
			$sql = "SELECT *
					FROM gmail WHERE mailid=:mail_id";
			if($stmt = $this->_db->prepare($sql)) {
				$stmt->bindParam(":mail_id", $mail_id, PDO::PARAM_STR);
				$stmt->execute();
				$row = $stmt->fetch();
				return $row;
			}
		}
		if(strstr($mail_id,$takethemail) != false){
			$sql = "SELECT *
					FROM takethemail WHERE mailid=:mail_id";
			if($stmt = $this->_db->prepare($sql)) {
				$stmt->bindParam(":mail_id", $mail_id, PDO::PARAM_STR);
				$stmt->execute();
				$row = $stmt->fetch();
				return $row;
			}
		}
		if(strstr($mail_id,$hotmail) != false){
			$sql = "SELECT *
					FROM hotmail WHERE mailid=:mail_id";
			if($stmt = $this->_db->prepare($sql)) {
				$stmt->bindParam(":mail_id", $mail_id, PDO::PARAM_STR);
				$stmt->execute();
				$row = $stmt->fetch();
				return $row;
			}
		}
		if(strstr($mail_id,$yahoo) != false){
			$sql = "SELECT *
					FROM yahoo WHERE mailid=:mail_id";
			if($stmt = $this->_db->prepare($sql)) {
				$stmt->bindParam(":mail_id", $mail_id, PDO::PARAM_STR);
				$stmt->execute();
				$row = $stmt->fetch();
				return $row;
			}
		}
   }
   
   	function stri_replace( $find, $replace, $string ) {
		//Case-insensitive str_replace()
	  	$parts = explode( strtolower($find), strtolower($string) );
	  	$pos = 0;
	  	foreach( $parts as $key=>$part ){
			$parts[ $key ] = substr($string, $pos, strlen($part));
			$pos += strlen($part) + strlen($find);
	  	}

 	 return( join( $replace, $parts ) );
	}


function txt2html($txt) {
// Transforms txt in html

  //Kills double spaces and spaces inside tags.
  while( !( strpos($txt,'  ') === FALSE ) ) $txt = str_replace('  ',' ',$txt);
  $txt = str_replace(' >','>',$txt);
  $txt = str_replace('< ','<',$txt);

  //Transforms accents in html entities.
  $txt = htmlentities($txt);

  //We need some HTML entities back!
  $txt = str_replace('"','"',$txt);
  $txt = str_replace('<','<',$txt);
  $txt = str_replace('>','>',$txt);
  $txt = str_replace('&','&',$txt);

  //Ajdusts links - anything starting with HTTP opens in a new window
  $txt = $this->stri_replace("<a href=\"http://","<a target=\"_blank\" href=\"http://",$txt);
  $txt = $this->stri_replace("<a href=http://","<a target=\"_blank\" href=http://",$txt);

  //Basic formatting
  $eol = ( strpos($txt,"\r") === FALSE ) ? "\n" : "\r\n";
  $html = '<p>'.str_replace("$eol$eol","</p><p>",$txt).'</p>';
  $html = str_replace("$eol","\n",$html);
  $html = str_replace("</p>","</p>\n\n",$html);
  $html = str_replace("<p></p>","<p> </p>",$html);

  //Wipes  after block tags (for when the user includes some html in the text).
  $wipebr = Array("table","tr","td","blockquote","ul","ol","li");

  for($x = 0; $x < count($wipebr); $x++) {

    $tag = $wipebr[$x];
    $html = $this->stri_replace("<$tag>
","<$tag>",$html);
    $html = $this->stri_replace("</$tag>
","</$tag>",$html);

  }

  return $html;
}


public function markAsRead($mail_id, $pass){
		
		$gmail = "@gmail.com";
		$hotmail = "@hotmail.com";
		$yahoo = "@yahoo.com";

		$imap_host = "";
        $port = 993;
        $secure = "ssl";
		$imap_folder = 'INBOX';
		$user_attachment_dir = dirname(__FILE__) . '/attachments';

		if(strstr($mail_id,$gmail) != false){
			$imap_host = "imap.google.com";
		}
		if(strstr($mail_id,$hotmail) != false){
			$imap_host = "imap-mail.outlook.com";
		}
		if(strstr($mail_id,$yahoo) != false){
			$imap_host = "imap.mail.yahoo.com";
		}
		
		if($imap_host == "") return;
		
		$connection_string = '{'. $imap_host . ':' . $port . '/imap/' . $secure . '}'. $imap_folder;
		$NewMails = array();
		try {
			$mailbox = new ImapMailbox($connection_string, $mail_id, $pass, $user_attachment_dir);
            $NewMails = $mailbox->searchMailBox('UNSEEN');
		}
        catch(Exception $ex) {
        	echo $ex->getMessage();
        }
		$mailbox->markMailsAsRead($NewMails);
}


	public function send_mail($mails){
		foreach($mails as $mail){
			$From = $mail['from_mail'];
			
			$FromInfo = $this->getAliasInfo($From);
			$PassWord = $FromInfo['password'];
			
			$ReplyTo = $From;
			$To = $mail['to_mail'];
			
			if($this->log_level>1){
                //echo "## Mail Sending from:" . $From . " to:" . $To . "<br/>";
            }
			
			$order  = 4;
    		$length = 1000;
    		$ptext  = 'alice';
    
    		if ($ptext) $text = file_get_contents("text/".$ptext.".txt");
			if(isset($text)) {
				$markov_table = generate_markov_table($text, $order);
				$markov = generate_markov_text($length, $markov_table, $order);
			}
			
			$arr = explode(' ',trim($markov));
	        $first_part = implode(" ", array_splice($arr, 3, 5));
			
			$Subject = $first_part;
			$AltBody = $markov;
			
			$Body = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"
					\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
					<html xmlns=\"http://www.w3.org/1999/xhtml\">
					<head>
						<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
						<title>Mail</title>
						<!-- TemplateEndEditable -->
						<!-- TemplateBeginEditable name=\"head\" -->
						<!-- TemplateEndEditable -->
					</head>
					<body>";
			$Body = $Body . $this->txt2html($markov);
			$Body = $Body . "<br/><br/> Cheers- <br/><br/>" . 'Max' . "<br/>";
			$Body = $Body . "</body> </html>";

			$SMTPhost = $FromInfo['host'];
			$SMTPAuth = true;
			$SMTPSecure = $FromInfo['secure'];
			$SMTPPort = $FromInfo['port'];
		
			if($this->log_level>4){
                $this->mailer->SMTPDebug = 3;
            }
			
			$this->mailer->ClearReplyTos();
			$this->mailer->ClearAttachments();
			$this->mailer->ClearAllRecipients();
			$this->mailer->ClearCustomHeaders();
			
			
			$this->mailer->From = $From;
			$this->mailer->FromName = 'Maxwell';
			
			$this->mailer->AddReplyTo($ReplyTo);
			$this->mailer->addAddress($To);
			
			$this->mailer->isHTML(true);
			
			$this->mailer->Subject = $Subject;
			$this->mailer->Body    = $Body;
			$this->mailer->AltBody    = $AltBody;
			
            $this->mailer->isSMTP();
            $this->mailer->Host = $SMTPhost;
            $this->mailer->SMTPAuth = $SMTPAuth;
            $this->mailer->Username = $From;
            $this->mailer->Password = $PassWord;
            $this->mailer->SMTPSecure = $SMTPSecure;
            $this->mailer->Port = $SMTPPort;
			
			
			//$this->markAsRead($From,$PassWord);
			
			
			
			//$ch = curl_init();
			//curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
			//curl_exec($ch);
			
			$failed = false;
            if(!$this->mailer->send()) $failed = true;
			
			$takethemail = "@takethemail.com";
			if(strstr($From,$takethemail) != false && $failed == false){
				echo "Message has been sent! from:". $From . " to:". $To ."<br/>";
// 				$message_id = $this->mailer->GetLastMessageID();
// 				$to_interval = 10;
// 				$to_time = date("Y-m-d H:i:s", strtotime("+{$to_interval} minutes", time()));
// 				$sql = "INSERT into send_mail values
// 					(:from, :to, :to_time, :message_id);";
// 	
// 					
// 				if($stmt = $this->_db->prepare($sql)) {
// 					$stmt->bindParam(":from", $To, PDO::PARAM_STR);
// 					$stmt->bindParam(":to", $From, PDO::PARAM_STR);
// 					$stmt->bindParam(":to_time", $to_time, PDO::PARAM_STR);
// 					$stmt->bindParam(":message_id", $message_id, PDO::PARAM_STR);
// 					$stmt->execute();
// 				}
			}
			else {
                echo "<font color=\"red\">Message sending failed! from:". $From . " to:". $To ."</font><br/>";
			}
       }
	}
}
?>